package com.bs.modules.app.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bs.common.exception.RRException;
import com.bs.common.utils.HttpHelper;
import com.bs.common.utils.RedisUtils;
import com.bs.common.validator.Assert;
import com.bs.modules.app.dao.UserDao;
import com.bs.modules.app.entity.UserEntity;
import com.bs.modules.app.form.LoginForm;
import com.bs.modules.app.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

  @Autowired
  private RedisUtils redisUtils;

  @Override
  public UserEntity queryByMobile(String mobile) {
    return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
  }

  @Override
  public long login(LoginForm form) {
    UserEntity user = queryByMobile(form.getMobile());
    Assert.isNull(user, "手机号或密码错误");

    //密码错误
    if (!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))) {
      throw new RRException("手机号或密码错误");
    }

    return user.getUserId();
  }

  @Override
  public JSONObject jscode2session(String appId, String secret, String jsCode) throws Exception {

    StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/jscode2session");

    url.append("?appid=")
      .append(appId)
      .append("&secret=")
      .append(secret)
      .append("&js_code=")
      .append(jsCode)
      .append("&grant_type=authorization_code");

    try {
      String resInfo = HttpHelper.httpGet(url.toString());
      log.info("请求微信返回参数:", resInfo);

      JSONObject ret = new JSONObject();
      com.alibaba.fastjson.JSONObject resInfoJson = com.alibaba.fastjson.JSONObject.parseObject(resInfo);

      ret.put("openid", resInfoJson.get("openid"));
      ret.put("session_key", resInfoJson.get("session_key"));

      // 存储登录信息
      redisUtils.set((String) resInfoJson.get("openid"), "1");

      return ret;
    } catch (Exception e) {
      log.info("请求微信失败参数", e);
      e.printStackTrace();
      throw new Exception("微信登录失败");
    }

  }


}
